package esa.android;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import android.content.SharedPreferences;
import android.util.Base64;

public class PrefencesStorage {

	private SharedPreferences settings;

	private Map<String, String> data = Collections.synchronizedMap(new HashMap<String,String>());
	
	public PrefencesStorage(SharedPreferences settings) {
		this.settings = settings;
	}

	public void putData(String key, Object value) {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		try {
			ObjectOutputStream oo = new ObjectOutputStream(output);
			oo.writeObject(value);
			oo.close();

			data.put(key, Base64.encodeToString(output.toByteArray(), Base64.DEFAULT));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public boolean commit() {
		SharedPreferences.Editor editor = settings.edit();
		for (String k: data.keySet()) {
			editor.putString(k, data.get(k));
		}
		editor.commit();

		return true;
	}

	public Object getData(String key, Object dfl) {
		String d = data.get(key);
		if (d == null) {
			d = settings.getString(key, null);
		}
		if (d == null)
			return dfl;
		
		byte[] b = Base64.decode(d, Base64.DEFAULT);
		ByteArrayInputStream input = new ByteArrayInputStream(b);
		try {
			ObjectInputStream oi = new ObjectInputStream(input);
			return oi.readObject();
		} catch (StreamCorruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return dfl;
	}
}
